import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_multiple_bottom_sheet.dart';
import 'package:safetymonitor/app/core/ext/ext.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/common/chart_data.dart';
import 'package:safetymonitor/app/data/entities/application/corporation_name_entity.dart';
import 'package:safetymonitor/app/data/entities/home/analysis/get_device_online_status_entity.dart';
import 'package:safetymonitor/app/data/entities/home/analysis/get_record_person_sort_entity.dart';
import 'package:safetymonitor/app/data/entities/home/analysis/get_risk_entity.dart';
import 'package:safetymonitor/modules/home/home_page/home_page_control.dart';
import 'package:safetymonitor/modules/home/statistical_analysis/dialog/dialog.dart';
import 'package:safetymonitor/router/app_pages.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class AttendanceData {
  AttendanceData({required this.company, required this.onTime, required this.missed});

  String company;
  num onTime;
  num missed;
}

///统计分析
class StatisticalAnalysisController extends GetxController {
  final List<AttendanceData> attendanceDataUp = [
    // AttendanceData(company: '金铅集团', onTime: 30.0, missed: 70.0),
    // AttendanceData(company: '矿山分公司', onTime: 35.0, missed: 65.0),
    // AttendanceData(company: '金铅汝阳', onTime: 40.0, missed: 60.0),
    // AttendanceData(company: '冶炼分公司', onTime: 45.0,  missed: 55.0),
    // AttendanceData(company: '化学分公司', onTime: 50.0, missed: 50.0),
    // AttendanceData(company: '金属分公司', onTime: 45.0, missed: 55.0),
    // AttendanceData(company: '金铅建设', onTime: 40.0, missed: 60.0),
    // AttendanceData(company: '金铅光明', onTime: 35.0, missed: 65.0),
    // AttendanceData(company: '物流分公司', onTime: 30.0, missed: 70.0),
    // AttendanceData(company: '技术中心', onTime: 25.0, missed: 75.0),
    // AttendanceData(company: '光华公司', onTime: 20.0, missed: 80.0),
  ];
  final List<AttendanceData> attendanceDataDown = [
    // AttendanceData(company: '金铅集团', onTime: 30.0, missed: 70.0),
    // AttendanceData(company: '矿山分公司', onTime: 35.0, missed: 65.0),
    // AttendanceData(company: '金铅汝阳', onTime: 40.0, missed: 60.0),
    // AttendanceData(company: '冶炼分公司', onTime: 45.0,  missed: 55.0),
    // AttendanceData(company: '化学分公司', onTime: 50.0, missed: 50.0),
    // AttendanceData(company: '金属分公司', onTime: 45.0, missed: 55.0),
    // AttendanceData(company: '金铅建设', onTime: 40.0, missed: 60.0),
    // AttendanceData(company: '金铅光明', onTime: 35.0, missed: 65.0),
    // AttendanceData(company: '物流分公司', onTime: 30.0, missed: 70.0),
    // AttendanceData(company: '技术中心', onTime: 25.0, missed: 75.0),
    // AttendanceData(company: '光华公司', onTime: 20.0, missed: 80.0),
  ];

  ///当前月份
  int currentUpMonthUp = 0;
  int currentUpMonthDown = 0;

  ///获取账号的当前公司名字
  String? userCompanyName;

  ///选择的公司(top)
  // String selectCompanyTop = '';

  ///选择的公司(center)
  String selectCompanyCenter = '';

  ///选择的公司(bottom)
  String selectCompanyBottom = '';

  ///主公司 写死（默认）
  String currentMainCompany = '金钼集团';

  // 选中的公司(top)
  // CorporationNameEntity? _selectIdTop;

  // 选中的公司（center）
  CorporationNameEntity? _selectIdCenter;

  // 选中的公司（bottom）
  CorporationNameEntity? _selectIdBottom;

  String getString(int i) {
    if (i == 0) {
      //top
      // if (_selectIdTop != null) {
      //   return _selectIdTop!.name!.trim();
      // }
    } else if (i == 1) {
      //center
      if (_selectIdCenter != null) {
        return _selectIdCenter!.name!.trim();
      }
    } else {
      //bottom
      if (_selectIdBottom != null) {
        return _selectIdBottom!.name!.trim();
      }
    }

    return '公司名';
  }

  @override
  void onInit() {
    super.onInit();
    //获取当前月份
    currentUpMonthUp = DateTime.now().month;
    currentUpMonthDown = DateTime.now().month;
    userCompanyName = UserManager.getUserCompanyName() ?? '';
    nameListY = Get.find<HomePageControl>().nameList;
    //浅拷贝
    nameListNO = List.from(nameListY);
    for (int i = 0; i < nameListNO.length; i++) {
      if (nameListNO[i].name == currentMainCompany) {
        nameListNO.remove(nameListNO[i]);
      }
    }
    // if (currentMainCompany == userCompanyName && nameList.isNotEmpty) {
    //只有是主公司才才取第一个 并获取数据
    // _selectId = nameList.first;
    // selectCompany = getString(0);
    // }
    // _selectIdTop = nameListY.first;
    // selectCompanyTop = getString(0);

    _selectIdCenter = nameListNO.first;
    selectCompanyCenter = getString(0);

    _selectIdBottom = nameListNO.first;
    selectCompanyBottom = getString(0);

    startDateUp = '${getUpFirstDayOfMonth(currentUpMonthUp)}';
    endDateUp = '${getUpLastDayOfMonth(currentUpMonthUp)}';
    startDateDown = '${getUpFirstDayOfMonth(currentUpMonthDown)}';
    endDateDown = '${getUpLastDayOfMonth(currentUpMonthDown)}';

    //值班签到率统计
    getRecordStatsPercent();
    // 值班计划执行率统计
    getRecordStats();
    // 企业风险统计
    getRiskAnalysis();
    // 监测设备统计分析
    getOnOffData();
  }

  ///获取月第一天
  // DateTime getFirstDayOfMonth(int month) {
  //   return DateTime(DateTime.now().year, month, 1);
  // }
  //
  // ///获取月第最后一天
  // DateTime getLastDayOfMonth(int month) {
  //   //将日期设置为零以获取上个月的最后一天，
  //   //这将是所需月份的最后一天。
  //   return DateTime(DateTime.now().year, month + 1, 0);
  // }

  ///获取上月第一天
  DateTime getUpFirstDayOfMonth(int month) {
    return DateTime(DateTime.now().year, month - 1, 1);
  }

  ///获取上月第最后一天
  DateTime getUpLastDayOfMonth(int month) {
    return DateTime(DateTime.now().year, month, 0);
  }

  // 人员出入情况数据
  List<String> personData = ['值班次数'];
  final List<PieData> pieData = [];

  /// 柱状图数据
  List<CartesianSeries<PieData, String>> barData = [];

  ///值班人员排名TOP10
  // void initBarData() async {
  //   pieData.clear();
  //   barData.clear();
  //   final res = await HttpUtil()
  //       .generateGetRequest<List<GetRecordPersonSortEntity>>(
  //           Interface.getRecordPersonSort,
  //           queryParameters: {
  //         'dutyTime':
  //             '${getFirstDayOfMonth(currentMonth)},${getLastDayOfMonth(currentMonth)}',
  //         'companyId': _selectIdTop?.id,
  //       }).execute();
  //   res.onSuccess((result) {
  //     if (result.data != null) {
  //       for (int i = 0; i < result.data!.length; i++) {
  //         pieData.add(
  //             PieData(result.data![i].name ?? '', result.data![i].count ?? 0));
  //       }
  //       barData.add(ColumnSeries<PieData, String>(
  //         dataSource: pieData,
  //         xValueMapper: (PieData data, _) => data.xData,
  //         yValueMapper: (PieData data, _) => data.yData,
  //         color: const Color(0xFF1847E3),
  //         //设置柱状图的宽度
  //         width: 0.2,
  //         name: personData[0],
  //       ));
  //       update(['top']);
  //     }
  //   });
  // }

  // Color _descColor(String nameC) {
  //   switch (nameC) {
  //     case '金钼集团':
  //       return const Color(0xFF628EFF);
  //     case '矿山分公司':
  //       return const Color(0xFF55B5F0);
  //     case '金木汝阳':
  //       return const Color(0xFF628EFF);
  //     case '五洲矿业':
  //       return const Color(0xFF54D09B);
  //     case '治炼分公司':
  //       return const Color(0xFFFF9A62);
  //     case '化学分公司':
  //       return const Color(0xFF38DCD3);
  //     case '金属分公司':
  //       return const Color(0xFFF4C64F);
  //     default:
  //       return Colors.red;
  //   }
  // }
  Color _descColor(String nameC) {
    switch (nameC) {
      case '金钼集团':
        return const Color(0xFF628EFF);
      case '矿山分公司':
        return const Color(0xFF55B5F0);
      case '金钼汝阳':
        return const Color(0xFF010612);
      case '五洲矿业':
        return const Color(0xFF54D09B);
      case '冶炼分公司':
        return const Color(0xFFFF9A62);
      case '化学分公司':
        return const Color(0xFF38DCD3);
      case '金属分公司':
        return const Color(0xFFF4C64F);
      //新增
      case '金钼建设':
        return const Color(0xFF1447CA);
      case '金钼光明':
        return const Color(0xFF03ED89);
      case '物流分公司':
        return const Color(0xFF933C05);
      case '技术中心':
        return const Color(0xFF05F4E7);
      case '华光公司':
        return const Color(0xFFF4B000);
      default:
        return Colors.red;
    }
  }

  //-------------------------------------Up-----------------------------------------------
  int get getRecordStatsListCount {
    return attendanceDataUp.fold(0, (previousValue, element) => previousValue + element.missed.toInt());
  }

  ///值班签到率统计 ?companyId=100&startTime=2024-09-03&endTime=2024-09-20
  void getRecordStatsPercent() async {
    attendanceDataUp.clear();
    final res = await HttpUtil().generateGetRequest<List<GetRecordPersonSortEntity>>(Interface.getRecordStatsPercent, queryParameters: {
      'startTime': startDateUp,
      'endTime': endDateUp,
      'companyId': UserManager.getUserCompanyId(),
    }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        for (int i = 0; i < result.data!.length; i++) {
          attendanceDataUp.add(AttendanceData(company: result.data![i].name, onTime: result.data![i].signedInPercent, missed: result.data![i].notSignedInPercent));
        }
        // 方式1反转（创建一个新的list）没有final
        // attendanceDataUp = attendanceDataUp.reversed.toList();
        // 方式2反转（创建一个新的list） 有final 通过setRange设置回去
        // attendanceDataUp.setRange(0, attendanceDataUp.length, attendanceDataUp.reversed);
        //  方式1反转（使用扩展方法）有final
        attendanceDataUp.reverseInPlace();
        update(['top']);
      }
    });
  }

  //-------------------------------------Up-----------------------------------------------
  //-------------------------------------Down-----------------------------------------------

  int get getRecordStatsListCountDown {
    return attendanceDataDown.fold(0, (previousValue, element) => previousValue + element.missed.toInt());
  }

  ///值班签到率统计 ?companyId=100&startTime=2024-11-07&endTime=2024-12-13
  void getRecordStats() async {
    attendanceDataDown.clear();
    final res = await HttpUtil().generateGetRequest<List<GetRecordPersonSortEntity>>(Interface.getRecordStats, queryParameters: {
      'startTime': startDateDown,
      'endTime': endDateDown,
      'companyId': UserManager.getUserCompanyId(),
    }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        for (int i = 0; i < result.data!.length; i++) {
          attendanceDataDown.add(AttendanceData(company: result.data![i].name, onTime: result.data![i].percent2, missed: result.data![i].notSignedInPercent));
        }
        // attendanceDataDown = attendanceDataDown.reversed.toList();
        attendanceDataDown.reverseInPlace();
        update(['top']);
      }
    });
  }

  //-------------------------------------Down-----------------------------------------------
  var initRiskData = <ChartData>[];

  var leftRiskData = <ChartData>[];

  // RiskControlAnalysisEntity? analysis;

  int get initRiskCount {
    return initRiskData.fold(0, (previousValue, element) => previousValue + element.y.toInt());
  }

  int get leftRiskCount {
    return leftRiskData.fold(0, (previousValue, element) => previousValue + element.y.toInt());
  }

  ///获取风险列表
  void getRiskList(String riskLevelCode,int riskType) async {
    attendanceDataDown.clear();
    final res = await HttpUtil().generateGetRequest<List<GetRiskEntity>>(Interface.getRiskPoint, queryParameters: {
      'companyId': _selectIdCenter?.id,
      'riskLevelCode': riskLevelCode,
      'riskType': riskType,
    }).execute(isShowLoading: true);
    res.onSuccess((result) {
      _showDialog(title: riskType==1?'安全生产':'环境监测', data: result.data??[]);
    });
  }


  /// 弹窗
  void _showDialog({required String title, required List<GetRiskEntity> data}) {
    showDialog(
      context: Get.context!,
      builder: (BuildContext context) {
        return StatisticalDialog(
          title: title,
          data: data,
        );
      },
    );
  }

  ///企业风险统计 安全
  void getRiskAnalysis() async {
    final resp = await Dio(BaseOptions(
      headers: {'Authorization': UserManager.getToken()},
    )).get(
      '${Interface.getRiskMap}?companyId=${_selectIdCenter?.id}&riskType=1',
    );
    if (resp.statusCode == 200) {
      try {
        final data = resp.data;
        final dataData = data['data'] as List?;
        if (dataData == null) return;
        final dataDataData = dataData[0]['data'] as List?;
        try {
          initRiskData.clear();
          initRiskData.addAll([
            ChartData('重大风险', dataDataData?[0]['重大风险'] as num, const Color(0xFFFD6B6B)),
            ChartData('较大风险', dataDataData?[1]['较大风险'] as num, const Color(0xFFFC9900)),
            ChartData('一般风险', dataDataData?[2]['一般风险'] as num, const Color(0xFFFFCE24)),
            ChartData('低风险', dataDataData?[3]['低风险'] as num, const Color(0xFF33A9FF)),
          ]);
          update(['center']);
        } catch (_) {}
      } catch (_) {}
    }

    final resp2 = await Dio(BaseOptions(
      headers: {'Authorization': UserManager.getToken()},
    )).get(
      '${Interface.getRiskMap}?companyId=${_selectIdCenter?.id}&riskType=2',
    );
    if (resp2.statusCode == 200) {
      try {
        final data = resp2.data;
        final dataData = data['data'] as List?;
        if (dataData == null) return;
        final dataDataData = dataData[0]['data'] as List?;
        try {
          leftRiskData.clear();
          leftRiskData.addAll([
            ChartData('重大风险', dataDataData?[0]['重大风险'] as num, const Color(0xFFFD6B6B)),
            ChartData('较大风险', dataDataData?[1]['较大风险'] as num, const Color(0xFFFC9900)),
            ChartData('一般风险', dataDataData?[2]['一般风险'] as num, const Color(0xFFFFCE24)),
            ChartData('低风险', dataDataData?[3]['低风险'] as num, const Color(0xFF33A9FF)),
          ]);
          update(['center']);
        } catch (_) {}
      } catch (_) {}
    }
  }

  //-------------------------------------------------

  //---------------------------------获取设备状态

  var leftRiskDataOnOff = <ChartData>[];

  int get leftRiskCountOnOff {
    return leftRiskDataOnOff.fold(0, (previousValue, element) => previousValue + element.y.toInt());
  }

  ///监测设备统计分析
  void getOnOffData() async {
    final resp = await HttpUtil().generateGetRequest<List<GetDeviceOnlineStatusEntity>>(Interface.getDeviceOnlineStatus, queryParameters: {
      'companyId': '${_selectIdBottom?.id}',
    }).execute();
    resp.onSuccess((result) {
      leftRiskDataOnOff.clear();
      if (result.data != null && result.data!.isNotEmpty) {
        leftRiskDataOnOff.addAll([
          ChartData(
            '在线',
            int.parse(result.data!.first.safeOnlineQuantity) + int.parse(result.data!.first.environmentalOnlineQuantity),
            const Color(0xFFFD6B6B),
          ),
          ChartData(
            '离线',
            int.parse(result.data!.first.safeOfflineQuantity) + int.parse(result.data!.first.environmentalOfflineQuantity),
            const Color(0xFFFC9900),
          ),
        ]);
      }
      update(['bottom']);
    });
  }

  ///------------------------获取公司------------------------------------------

  // 公司列表（不含总公司）
  List<CorporationNameEntity> nameListNO = [];

  // 公司列表（含总公司）
  List<CorporationNameEntity> nameListY = [];

  // 选取公司
  void selectCompanyOn(int i) {
    if (i == 0) {
      //top
      // CustomEquipmentBottomSheet<CorporationNameEntity>(
      //   dataList: nameListY,
      //   checkedList: _selectIdTop != null ? [_selectIdTop!] : [],
      //   onConfirm: (value) {
      //     if (value.isNotEmpty) {
      // _selectIdTop = value[0];
      // selectCompanyTop = getString(i);
      //值班人员排名TOP10
      // initBarData();
      //个的那位值班情况统计
      // getRecordStatsList();
      // }
      // },
      // title: '选择公司',
      // isMultiple: false,
      // ).showBottomSheetDialog();
    } else if (i == 1) {
      //center
      CustomEquipmentBottomSheet<CorporationNameEntity>(
        dataList: nameListNO,
        checkedList: _selectIdCenter != null ? [_selectIdCenter!] : [],
        onConfirm: (value) {
          if (value.isNotEmpty) {
            _selectIdCenter = value[0];
            selectCompanyCenter = getString(i);
            //企业风险统计 安全
            getRiskAnalysis();
          }
        },
        title: '选择公司',
        isMultiple: false,
      ).showBottomSheetDialog();
    } else {
      //bottom
      CustomEquipmentBottomSheet<CorporationNameEntity>(
        dataList: nameListNO,
        checkedList: _selectIdBottom != null ? [_selectIdBottom!] : [],
        onConfirm: (value) {
          if (value.isNotEmpty) {
            _selectIdBottom = value[0];
            selectCompanyBottom = getString(i);
            // 监测设备统计分析
            getOnOffData();
          }
        },
        title: '选择公司',
        isMultiple: false,
      ).showBottomSheetDialog();
    }
  }

  ///打开设备在线离线列表页面
  void openOnOffDevicePage(int seriesIndex) {
    Get.toNamed(Routes.onOfflineDevice, arguments: {'id': _selectIdBottom?.id, 'index': seriesIndex}); //当前选中的公司id
  }

//---------------------------值班签到统计------------------------------
  String endDateUIUp = '点击时间段筛选';

  ///默认true选中
  bool pieChartMonthUp = true;
  bool pieCharTimeRangeUp = false;

  ///结束时间
  String endDateUp = '';

  ///开始时间
  String startDateUp = '';

  ///点击本月
  void onClickMonthUp() {
    if (pieChartMonthUp) {
      return;
    }
    endDateUIUp = '点击时间段筛选';
    startDateUp = '${getUpFirstDayOfMonth(currentUpMonthUp)}';
    endDateUp = '${getUpLastDayOfMonth(currentUpMonthUp)}';
    pieChartMonthUp = true;
    pieCharTimeRangeUp = false;
    getRecordStatsPercent();
    update(['top']);
  }

  ///点击时间范围
  void onClickTimeRangeUp() {
    pieCharTimeRangeUp = true;
    pieChartMonthUp = false;
    getRecordStatsPercent();
    update(['top']);
  }

  /// 默认开始时间  null传入也是开始时间
  selectTimeUp() async {
    final DateTimeRange? picked = await showDateRangePicker(
      context: Get.context!,
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
      currentDate: DateTime.now(),
      saveText: '确定',
    );

    if (picked != null) {
      startDateUp = picked.start.toDateStr;
      endDateUp = picked.end.toDateStr;
      endDateUIUp = '$startDateUp-$endDateUp';
      onClickTimeRangeUp();
    }
  }

//---------------------------值班计划执行率统计------------------------------
  String endDateUIDown = '点击时间段筛选';

  ///默认true选中
  bool pieChartMonthDown = true;
  bool pieCharTimeRangeDown = false;

  ///结束时间
  String endDateDown = '';

  ///开始时间
  String startDateDown = '';

  ///点击本月
  void onClickMonthDown() {
    if (pieChartMonthDown) {
      return;
    }
    endDateUIDown = '点击时间段筛选';
    startDateDown = '${getUpFirstDayOfMonth(currentUpMonthDown)}';
    endDateDown = '${getUpLastDayOfMonth(currentUpMonthDown)}';
    pieChartMonthDown = true;
    pieCharTimeRangeDown = false;
    getRecordStats();
    update(['top']);
  }

  ///点击时间范围
  void onClickTimeRange() {
    pieCharTimeRangeDown = true;
    pieChartMonthDown = false;
    getRecordStats();
    update(['top']);
  }

  /// 默认开始时间  null传入也是开始时间
  selectTimeDown() async {
    final DateTimeRange? picked = await showDateRangePicker(
      context: Get.context!,
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
      currentDate: DateTime.now(),
      saveText: '确定',
    );

    if (picked != null) {
      startDateDown = picked.start.toDateStr;
      endDateDown = picked.end.toDateStr;
      endDateUIDown = '$startDateDown-$endDateDown';
      onClickTimeRange();
    }
  }

  // 企业风险统计详情接口
  void getRiskAnalysisDetails() {
    if (_selectIdCenter == null) {
      return;
    }
  }
}

///列表数据反转
///这个扩展方法通过双指针的方式交换列表两端的元素，实现了原地反转。
///使用 .. 级联操作调用 reverseInPlace()，可以直接链式操作。
extension ListExtensions<E> on List<E> {
  void reverseInPlace() {
    for (int i = 0, j = length - 1; i < j; i++, j--) {
      final temp = this[i];
      this[i] = this[j];
      this[j] = temp;
    }
  }
}
